<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>取消请求</title>
</head>
<body>
  <button onclick="getProducts1()">获取商品列表1</button><br>
  <button onclick="getProducts2()">获取商品列表2</button><br>
  <button onclick="cancelReq()">取消请求</button><br>

  <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
  <script>
    axios.defaults.baseURL = 'http://localhost:4000'
    let cancel; // 用于存储取消请求函数

    // 请求拦截器
    axios.interceptors.request.use(config => {
      // 发送请求前先判断是否有cancel函数
      if(cancel) {
       cancel('强制取消')
      }
      config.cancelToken = new axios.CancelToken((c) => { // 在cancelToken中同步执行
        cancel = c
      })

      return config // 必须返回
    })
    
    // 响应拦截器
    axios.interceptors.response.use(response => {
      cancel = null
      return response
    }, error => {
      if(axios.isCancel(error)) {
        alert('取消请求:' + error.message)
      } else {
        cancel = null
        alert('请求出错:' + error.message)
      }
      return new Promise(() => {}) // 返回一个pending状态的promise,中断promise链
    })



    
    function getProducts1() {
     
      axios('/getProducts1').then(
        response => {
          console.log('1111 onRsolved()', response.data)
        },
        error => {
          
        }
      )
    }

    function getProducts2() {
      axios('/getProducts22').then(
        response => console.log('2222 onRsolved()', response.data),
        error =>{
          
        }
      )
    }

    function cancelReq() {
      if(cancel) {
        cancel('强制取消')
      }
    }
  </script>
</body>
</html>